package com.minglan.gfx.app.upload.service.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import com.minglan.gfx.app.upload.service.FileStorageService;

@Service("/fileStorageService")
public class FileStorageServiceImpl implements FileStorageService {

	private final Path path=Paths.get("fileStorage");
	//TODO 上传目录应该取自配置
	
	/**
	 * 初始化目录
	 */
	public void init() {
		try {
			Files.createDirectory(path);
		} catch (IOException e) {
			throw new RuntimeException("could not init folder for upload");
		}	
	}

	/**
	 * 上传文件
	 */
	public void save(MultipartFile multipartFile) {
		try {
			Files.copy(multipartFile.getInputStream(), this.path.resolve(multipartFile.getOriginalFilename()));
		} catch (IOException e) {
			throw new RuntimeException("Could not sotre the file. Error:"+e.getMessage());
		}	
	}

	/**
	 * 下载文件
	 */
	public Resource load(String filename) {
		Path file =path.resolve(filename);
		try {
			Resource resource = new UrlResource(file.toUri());
			if (resource.exists() && resource.isReadable()) {
				return resource;
			} else {
				throw new RuntimeException("Could not get file :" + filename);
			} 
		} catch (Exception e) {
			throw new RuntimeException("Error :"+e.getMessage());
		}
		
	}

	public Stream<Path> load() {
		try {
			return Files.walk(this.path, 1).filter(path->!path.equals(this.path)).map(this.path::relativize);
		} catch (IOException e) {
			throw new RuntimeException("Error : "+e.getMessage());
		}

	}

	/**
	 * 清除文件目录
	 */
	public void clear() {
		FileSystemUtils.deleteRecursively(path.toFile());
	}

}
